using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using QFramework;
using TMPro;

namespace Survivor
{
	public partial class UpgradePanel : UIElement,IController
	{
		private List<Button> _upgradeButtons;
		private void Awake()
		{
			_upgradeButtons = new();
			Global.Coin.RegisterWithInitValue((value) =>
			{
				TextCoins.text = "Coins:" + value;
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
						
			BtnCloseUpgradePanel.onClick.AddListener(() =>
			{
				Hide();
			});
			
                

			this.GetSystem<CoinUpgradeSystem>().Items.ForEach((item) =>
			{
				BtnUpgradeItemTemplate.InstantiateWithParent(UpgradeItemRoot).Self((self) =>
				{
					_upgradeButtons.Add(self);
					var itemCache = item;
					string costText = item.Level < item.MaxLevel ? $"{item.Price}coins" : "Max";
					self.GetComponentInChildren<TextMeshProUGUI>().text = item.Description+$"Lv.{item.Level}({costText})";
					self.onClick.AddListener(() =>
					{
						itemCache.Upgrade();
						AudioKit.PlaySound("AbilityLevelUp");
						FlushUI();
					});
				}).Show();
			});
			FlushUI();
		}

		protected override void OnShow()
		{
			base.OnShow();
			FlushUI();
		}

		public void FlushUI()
		{
			var items = this.GetSystem<CoinUpgradeSystem>().Items;
			for (int i = 0; i < items.Count; i++)
			{
				if (items[i].Price > Global.Coin.Value || items[i].Level >= items[i].MaxLevel)
				{
					_upgradeButtons[i].enabled = false;
				}
				else
				{
					_upgradeButtons[i].enabled = true;
				}
				_upgradeButtons[i].GetComponentInChildren<TextMeshProUGUI>().text = items[i].Description+$"Lv.{items[i].Level}({items[i].Price}coins)";
			}
		}

		protected override void OnBeforeDestroy()
		{
		}

		public IArchitecture GetArchitecture()
		{
			return Global.Interface;
		}
	}
}